package org.m2acsi.boundary;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.m2acsi.entities.Document;
import org.m2acsi.entities.Message;
import org.m2acsi.entities.Message_;
import org.m2acsi.entities.Task;

@Stateless
public class MessageEJB extends BaseEJB<Message> {

    @PersistenceContext(unitName = "taskManagerPU")
    EntityManager em;

    public MessageEJB() {
        super(Message.class);
    }

    public void save(Document document) {
        em.persist(document);
    }

    @Override
    public void remove(Message entity) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public EntityManager em() {
        return em;
    }

    public List<Message> getMessages(Task task) {
        CriteriaBuilder cBuilder = em.getCriteriaBuilder();
        CriteriaQuery<Message> cQuery = cBuilder.createQuery(entityClass);
        Root<Message> m = cQuery.from(entityClass);
        cQuery.select(m);
        cQuery.where(cBuilder.equal(m.get(Message_.task), task));
        cQuery.orderBy(cBuilder.desc(m.get(Message_.creationDate)));

        return em.createQuery(cQuery).getResultList();
    }
}
